﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EZMemoLib;
using System.Windows.Media.Animation;
using Microsoft.Win32;
using System.Timers;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;

namespace Remember.WPF.Views
{
    /// <summary>
    /// Interaction logic for ItemCard.xaml
    /// </summary>
    public partial class ItemEdit : UserControl
    {
        public event EventHandler OnClose;
        public MemoItem _Item;

        public MemoItem CurrentItem
        {
            set {
                _Item = value;
                Bind();
            }
        }

        bool IsChanged = false;

        DoubleAnimation animFadeIn = new DoubleAnimation();
        DoubleAnimation animFadeOut = new DoubleAnimation();

        public ItemEdit()
        {
            InitializeComponent();

            MediaElementInit();
            TimerInit();

            Bind();

            animFadeIn = new DoubleAnimation();
            animFadeIn.From = 0;
            animFadeIn.To = 1;
            animFadeIn.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
            this.BeginAnimation(OpacityProperty, animFadeIn);

            animFadeOut = new DoubleAnimation();
            animFadeOut.From = 1;
            animFadeOut.To = 0;
            animFadeOut.Duration = new Duration(TimeSpan.FromMilliseconds(500));
        }

        void Bind()
        {
            IsChanged = false;

            listBooks.DisplayMemberPath = "CategoryName";
            listBooks.SelectedValuePath  = "CategoryID";

            listFlow.ItemsSource = Player.GetPlayFlows();
            listFlow.DisplayMemberPath = "FlowName";
            listFlow.SelectedValuePath = "FlowMark";

            if (_Item != null)
            {
                if (_Item.Book != null)
                {
                    string loginID = (Context.Login != null) ? Context.Login.LoginID : string.Empty;
                    player = Player.Instance( loginID, _Item.Book.Value);
                }
                
                if (_Item.Book != null && _Item.Book.Value  > 0)
                {

                    listBooks.ItemsSource = BookBusiness.Instance().GetLessonList(_Item.Book.Value );

                    if (_Item.Category != null)
                    {
                        listBooks.SelectedValue = _Item.Category.Value;
                    }
                }

                this.listFlow.SelectedValue = _Item.ItemFlow;

                this.uiAnswer.Text = _Item.ItemAnswer;
                this.uiQuestion.Text = _Item.ItemQuestion ;
                this.uiRelation.Text = _Item.ItemRelation;

                this.uiSound.ToolTip = "Sound: " + _Item.ItemSound;

                VoicePart part = player.GetVoicePartFromItem(_Item);
                if (part != null)
                {
                    VoiceUrl = part.FilePath;
                    this.uiSound.Text = part.FilePath;
                    this.uiSoundStart.Text = part.PartStart.ToString("g");
                    this.uiSoundEnd.Text = part.PartEnd.ToString("g");

                    this.sliderSound.SelectionStart = part.PartStart.TotalSeconds;
                    this.sliderSound.SelectionEnd = part.PartStart.TotalSeconds;
                }

                this.uiPicturePath.Text = _Item.ItemPicture;
                this.uiDesc.Text = _Item.ItemDesc;

                this.uiOrderNumber.Text = _Item.ItemOrder.ToString();
            }
        }

        void Clean()
        {
            this.uiAnswer.Text = "";
            this.uiQuestion.Text = "";
            this.uiRelation.Text = "";

            this.uiSound.Text = "";

            string soundFull = "0:00:00.00";
            string soundStart = "0:00:000"; // 
            string soundEnd = soundFull;//"0:00:000"; // 
            this.uiSoundStart.Text = soundStart;
            this.uiSoundEnd.Text = soundEnd;

            this.uiPicturePath.Text = "";
            this.uiDesc.Text = "";

            this.uiOrderNumber.Text = "0";
        }


        void Pickup()
        {
            if (_Item != null)
            {
                _Item.ItemAnswer = this.uiAnswer.Text.Trim();
                _Item.ItemQuestion = this.uiQuestion.Text;
                _Item.ItemRelation = this.uiRelation.Text;

                if (this.listFlow.SelectedIndex >= 0)
                {
                    _Item.ItemFlow = string.Format ( "{0}", this.listFlow.SelectedValue);
                }

                if (this.listBooks.SelectedIndex >= 0)
                {
                    if ((int)this.listBooks.SelectedValue > 0)
                    {
                        _Item.Category = (int)this.listBooks.SelectedValue;
                    }
                }

                string soundStart = this.uiSoundStart.Text;
                string soundEnd = this.uiSoundEnd.Text;
                _Item.ItemSound = Player.BuildVoicePart(new VoicePart { PartStart = Player.ParseTimeSpan(soundStart), PartEnd = Player.ParseTimeSpan(soundEnd), FileMark = "L" });
                //_Item.ItemSound = this.uiSound.Text;

                _Item.ItemDesc = this.uiDesc.Text;

                _Item.ItemPicture = this.uiPicturePath.Text;

                long order = _Item.ItemOrder;
                long.TryParse(this.uiOrderNumber.Text, out order);
                if (order > 0)
                {
                    _Item.ItemOrder = order;
                }
            }
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        Player player;
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (_Item != null)
            {
                Pickup();

                if (player != null)
                {
                    player.SaveItem(_Item);
                }
            }

        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            bool Continue = false;
            if (this.IsChanged)
            {
                var rs = MessageBox.Show("This Item was modified, Are you save it?", "Item was changed", MessageBoxButton.YesNoCancel);
                if (rs == MessageBoxResult.Yes)
                {
                    btnSave_Click(sender, e);
                }

                if (rs != MessageBoxResult.Cancel)
                { Continue = true; }
            }
            else
            {
                Continue = true;
            }

            if (Continue)
            {
                if (this.OnClose != null)
                {
                    OnClose(sender, e);
                }
            }
        }

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            bool Continue = false ;
            if (this.IsChanged)
            {
                var rs = MessageBox.Show("This Item was modified, Are you save it?", "Item was changed", MessageBoxButton.YesNoCancel);
                if (rs == MessageBoxResult.Yes)
                {
                    btnSave_Click(sender, e);
                }

                if (rs != MessageBoxResult.Cancel)
                { Continue = true; }
            }
            else
            {
                Continue = true;
            }

            if (Continue)
            {
                this._Item = new MemoItem();
                Clean();
            }

        }

        private void btnPreview_Click(object sender, RoutedEventArgs e)
        {

        }

        string VoiceFilePath = null;
        string VoiceUrl = "Default/L_9.mp3";
        private void btnSoundFileBroswer_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Sound Files(*.mp3;*.wma)|*.mp3;*.wma";

            var rc = dlg.ShowDialog ();
            if (rc != null && rc.Value)
            { 
                VoiceFilePath = dlg.FileName ;
                uiSound.Text = VoiceFilePath;
            }
        }

        void Play()
        {
            mediaElement1.Source = new Uri(VoiceUrl, UriKind.Relative);
            mediaElement1.LoadedBehavior = MediaState.Manual;
            mediaElement1.Position = new TimeSpan(0, 0, 32);
            mediaElement1.Play();

        }

        private void btnVoiceStop_Click(object sender, RoutedEventArgs e)
        {
            posTimer.Stop();
            partTimer.Stop();
            mediaElement1.Stop();
            sliderSound.Value = 0;

            btnVoicePlay.Content = VoicePlayContent;
            btnVoicePlay.Tag = "";

        }

        private void btnVoicePause_Click(object sender, RoutedEventArgs e)
        {
            posTimer.Stop();
            partTimer.Stop();
            mediaElement1.Pause ();

        }

        string VoicePlayContent = null;
        string SoundFinderPlayContent = null;
        /// <summary>
        /// test play, start from start to end
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVoicePlay_Click(object sender, RoutedEventArgs e)
        {
            string voicePlayTag = btnVoicePlay.Tag != null?btnVoicePlay.Tag.ToString ():"";
            if (voicePlayTag != "S")
            {
                VoicePlayContent = btnVoicePlay.Content.ToString ();
                btnVoicePlay.Content = "Pause";
                btnVoicePlay.Tag = "S";
            }
            else
            {
                btnVoicePlay.Content = VoicePlayContent;
                btnVoicePlay.Tag = "P";

                btnVoicePause_Click(sender, e);

                return;
            }

            mediaElement1.LoadedBehavior = MediaState.Manual;

            TimeSpan ts = Player.ParseTimeSpan(uiSoundEnd.Text) - Player.ParseTimeSpan(uiSoundStart.Text);
            if (ts != null)
            {
                partTimer.Interval = ts;
                partTimer.Start();
            }

            if (!string.IsNullOrEmpty(VoiceFilePath))
            {
                mediaElement1.Source = new Uri(VoiceFilePath, UriKind.Absolute);
            }
            else
            {
                mediaElement1.Source = new Uri(VoiceUrl, UriKind.Relative);
            }

            if (voicePlayTag == "")
            {

                mediaElement1.Play();
                mediaElement1.Position = Player.ParseTimeSpan(uiSoundStart.Text);               
            }
            else
            {
                //pause -> replay

                mediaElement1.Play();

                if (currentPos != null)
                {
                    mediaElement1.Position = currentPos.Value;
                }
                
            }

            posTimer.Start();
        }

        void partTimer_Tick(object sender, EventArgs e)
        {
            mediaElement1.Stop();
            partTimer.Stop();
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            var pos = mediaElement1.Position;
            mediaElement1.Position = pos - TimeSpan.FromSeconds(10);
        }

        private void btnForword_Click(object sender, RoutedEventArgs e)
        {
            var pos = mediaElement1.Position;
            mediaElement1.Position = pos + TimeSpan.FromSeconds(10);

        }

        private void btnSoundFinderStop_Click(object sender, RoutedEventArgs e)
        {
            posTimer.Stop();
            partTimer.Stop();
            mediaElement1.Stop();
            sliderSound.Value = 0;

            btnSoundFinderPlay.Content = SoundFinderPlayContent;
            btnSoundFinderPlay.Tag = "";
        }

        private void btnSoundFinderPlay_Click(object sender, RoutedEventArgs e)
        {
            string tag = btnSoundFinderPlay.Tag != null ? btnSoundFinderPlay.Tag.ToString() : "";
            if (tag != "S")
            {
                btnSoundFinderPlay.Content = "Pause";
                btnSoundFinderPlay.Tag = "S";
            }
            else
            {
                btnSoundFinderPlay.Content = SoundFinderPlayContent;
                btnSoundFinderPlay.Tag = "P";

                mediaElement1.Pause();

                return;
            }

            mediaElement1.LoadedBehavior = MediaState.Manual;

            if (!string.IsNullOrEmpty(VoiceFilePath))
            {
                mediaElement1.Source = new Uri(VoiceFilePath, UriKind.Absolute);
            }
            else
            {

                mediaElement1.Source = new Uri(VoiceUrl, UriKind.Relative);
            }
            
            mediaElement1.Play();

            posTimer.Start();

            if (tag != "")
            {
                if (currentPos != null)
                {
                    mediaElement1.Position = currentPos.Value;
                }
            }
            
        }

        void MediaElementInit()
        {
            VoicePlayContent = btnVoicePlay.Content.ToString();
            SoundFinderPlayContent = btnSoundFinderPlay.Content.ToString();

            this.mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1_MediaOpened);
            this.mediaElement1.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);

            this.sliderSound.MouseEnter += new MouseEventHandler(sliderSound_MouseEnter);
            
        }

        void sliderSound_MouseEnter(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && e.MouseDevice.Captured ==null)
            {
                this.isDropped = true;
            }
        }



        void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            btnVoicePlay.Content = VoicePlayContent;
            btnVoicePlay.Tag = "";

            btnVoicePlay.Content = VoicePlayContent;
            btnVoicePlay.Tag = "";

        }

        void mediaElement1_MediaOpened(object sender, RoutedEventArgs e)
        {
            if (mediaElement1.NaturalDuration.HasTimeSpan)
            {
                var pos = mediaElement1.NaturalDuration.TimeSpan;
                uiDuration.Content = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", pos.Hours, pos.Minutes, pos.Seconds, pos.Milliseconds);

                sliderSound.Maximum = pos.TotalSeconds ;
                sliderSound.SmallChange = 1;
                //sliderSound.LargeChange = Math.Min(10, pos.Seconds / 10);
            }
            
            posTimer.Start();

            mediaElement1.Position = Player.ParseTimeSpan(uiSoundStart.Text);
        }

        bool isDropped = false;

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            object source = e.OriginalSource;


            if (isDropped )
            {
                isDropped = false;
                double seconds = mediaElement1.NaturalDuration.TimeSpan.TotalSeconds;

                double time = seconds / this.sliderSound.Maximum * this.sliderSound.Value;
                if (e.NewValue != e.OldValue)   
                {
                    mediaElement1.Position = new TimeSpan(0, 0, (int)e.NewValue);
                    time = e.NewValue; //reset flag     

                }

                mediaElement1.Position = new TimeSpan(0, 0, (int)time);
            }
        }


        void TimerInit()
        {
            posTimer.Interval = new TimeSpan ( 0,0,1);
            posTimer.Tick += new EventHandler(posTimer_Tick);

            partTimer.Tick += new EventHandler(partTimer_Tick);
        }

        void posTimer_Tick(object sender, EventArgs e)
        {
            var pos = mediaElement1.Position;
            currentPos = pos;
            uiMoniter.Content = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", pos.Hours, pos.Minutes, pos.Seconds, pos.Milliseconds);

            if (sliderSound.Maximum > 0)
            {
                sliderSound.Value = pos.TotalSeconds;
            }

            if (sliderSound.SelectionStart > 0)
            {
                sliderSound.SelectionEnd = pos.TotalSeconds;
            }
        }

        TimeSpan? currentPos = null;
        DispatcherTimer posTimer = new DispatcherTimer();
        DispatcherTimer partTimer = new DispatcherTimer();
 
        private void btnSoundFoundStart_Click(object sender, RoutedEventArgs e)
        {
            var pos = mediaElement1.Position;
            sliderSound.SelectionStart = pos.TotalSeconds;
            this.uiSoundStart.Text = string.Format("{0}:{1}:{2}.{3}", pos.Hours, pos.Minutes, pos.Seconds, pos.Milliseconds); 
        }

        private void btnSoundFoundEnd_Click(object sender, RoutedEventArgs e)
        {
            var pos = mediaElement1.Position;
            sliderSound.SelectionEnd = pos.TotalSeconds;
            this.uiSoundEnd.Text = string.Format("{0}:{1}:{2}.{3}", pos.Hours, pos.Minutes, pos.Seconds, pos.Milliseconds);
        }

        private void checkSelectPart_Click(object sender, RoutedEventArgs e)
        {
            if (checkSelectPart.IsChecked != null && checkSelectPart.IsChecked.Value)
            {
                this.canSelectPart.BeginAnimation(OpacityProperty, animFadeIn);
            }
            else
            {
                this.canSelectPart.BeginAnimation(OpacityProperty, animFadeOut);
            }
        }



    }
}
